package al73setZeroes;

import java.util.Arrays;
import java.util.HashSet;

public class SetZeroes73 {

/*    O(m+n)空间复杂度
    public static void setZeroes(int[][] matrix) {

        int[] row = new int[matrix.length];
        int[] column = new int[matrix[0].length];

*//*        HashSet<Integer> rowSet = new HashSet<>();
        HashSet<Integer> columnSet = new HashSet<>();*//*

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if(matrix[i][j] == 0){
                    row[i]=1;
                    column[j]=1;
                }
            }
        }

        for (int i = 0; i < matrix.length;  i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if(row[i]==1 || column[j]==1)
                    matrix[i][j] = 0;
            }
        }

    }*/

    public static void setZeroes(int[][] matrix) {
        boolean row_flag = false;
        int row = matrix.length;
        int col = matrix[0].length;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if(row_flag==false && i==0 && matrix[i][j] == 0){
                    row_flag = true;
                }
                if(i!=0 && matrix[i][j] == 0){
                    matrix[0][j] = matrix[i][0] = 0;
                }
            }
        }

        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }


        if (matrix[0][0] == 0){
            for (int i = 0; i < row; i++) {
                matrix[i][0] = 0;
            }
        }
        if (row_flag){
            for (int j = 0; j < col; j++) {
                matrix[0][j] = 0;
            }
        }

    }


    public static void main(String[] args) {
/*        int[][] nums = {{1,1,1},
                        {1,0,1},
                        {1,1,1}};*/
        int[][] nums = {{-4,-2147483648,6,-7,0},
                        {-8,6,-8,-6,0},
                        {2147483647,2,-9,-6,-10}};
/*        int[][] nums = {{0,1}};*/
        setZeroes(nums);

        // 使用循环遍历输出二维数组
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[i].length; j++) {
                System.out.print(nums[i][j] + " ");
            }
            System.out.println(); // 换行
        }
    }
}
